import express from 'express';
import bcrypt from 'bcryptjs';
import { body, validationResult } from 'express-validator';
import { executeQuery, getOne, transaction } from '../config/database.js';
import { authenticateToken, requireAdmin } from '../middleware/auth.js';

const router = express.Router();

// 获取所有用户（仅管理员）
router.get('/', authenticateToken, requireAdmin, async (req, res) => {
  try {
    const { role, page = 1, limit = 10 } = req.query;
    const pageNum = parseInt(page) || 1;
    const limitNum = parseInt(limit) || 10;
    const offset = (pageNum - 1) * limitNum;

    let sql = `
      SELECT id, username, name, role, phone, created_at 
      FROM users 
    `;
    let params = [];

    if (role && ['admin', 'teacher', 'driver', 'after_school_teacher'].includes(role)) {
      sql += ' WHERE role = ?';
      params.push(role);
    }

    sql += ` ORDER BY created_at DESC LIMIT ${limitNum} OFFSET ${offset}`;
    
    const users = await executeQuery(sql, params);

    // 获取总数
    let countSql = 'SELECT COUNT(*) as total FROM users';
    let countParams = [];
    
    if (role && ['admin', 'teacher', 'driver', 'after_school_teacher'].includes(role)) {
      countSql += ' WHERE role = ?';
      countParams.push(role);
    }
    
    const totalResult = await getOne(countSql, countParams);

    res.json({
      success: true,
      data: {
        users,
        pagination: {
          page: pageNum,
          limit: limitNum,
          total: totalResult.total,
          pages: Math.ceil(totalResult.total / limitNum)
        }
      }
    });

  } catch (error) {
    console.error('获取用户列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 创建用户（仅管理员）
router.post('/', [
  authenticateToken,
  requireAdmin,
  body('username').trim().isLength({ min: 3 }).withMessage('用户名至少3位'),
  body('password').isLength({ min: 6 }).withMessage('密码至少6位'),
  body('name').trim().notEmpty().withMessage('姓名不能为空'),
  body('role').isIn(['admin', 'teacher', 'driver', 'after_school_teacher']).withMessage('无效的角色'),
  body('phone').optional().isMobilePhone('zh-CN').withMessage('手机号格式不正确'),

], async (req, res) => {
  try {
    // 验证输入
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '输入验证失败',
        errors: errors.array()
      });
    }

    const { username, password, name, role, phone } = req.body;

    // 检查用户名是否已存在
    const existingUser = await getOne(
      'SELECT id FROM users WHERE username = ?',
      [username]
    );

    if (existingUser) {
      return res.status(400).json({
        success: false,
        message: '用户名已存在'
      });
    }

    // 创建用户 (暂时使用明文密码)
    const result = await executeQuery(`
      INSERT INTO users (username, password, name, role, phone) 
      VALUES (?, ?, ?, ?, ?)
    `, [username, password, name, role, phone]);

    res.status(201).json({
      success: true,
      message: '用户创建成功',
      data: {
        id: result.insertId,
        username,
        name,
        role
      }
    });

  } catch (error) {
    console.error('创建用户错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 获取教师列表
router.get('/teachers', authenticateToken, async (req, res) => {
  try {
    const teachers = await executeQuery(`
      SELECT 
        u.id, u.username, u.name, u.phone,
        COALESCE(GROUP_CONCAT(CONCAT(c.name, '(', c.grade, ')') SEPARATOR ', '), '') as classes
      FROM users u
      LEFT JOIN teacher_classes tc ON u.id = tc.teacher_id
      LEFT JOIN classes c ON tc.class_id = c.id
      WHERE u.role = 'teacher'
      GROUP BY u.id, u.username, u.name, u.phone
      ORDER BY u.name
    `);

    res.json({
      success: true,
      data: teachers
    });

  } catch (error) {
    console.error('获取教师列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 获取司机列表
router.get('/drivers', authenticateToken, async (req, res) => {
  try {
    const drivers = await executeQuery(`
      SELECT 
        u.id, u.name, u.phone,
        u.license_no, u.bus_no
      FROM users u
      WHERE u.role = 'driver'
      ORDER BY u.name
    `);

    res.json({
      success: true,
      data: drivers
    });

  } catch (error) {
    console.error('获取司机列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 获取课后老师列表
router.get('/after-school-teachers', authenticateToken, async (req, res) => {
  try {
    const teachers = await executeQuery(`
      SELECT 
        u.id, u.username, u.name, u.phone,
        COALESCE(GROUP_CONCAT(ac.name SEPARATOR ', '), '') as classes
      FROM users u
      LEFT JOIN after_school_classes ac ON u.id = ac.teacher_id
      WHERE u.role = 'after_school_teacher'
      GROUP BY u.id, u.username, u.name, u.phone
      ORDER BY u.name
    `);

    res.json({
      success: true,
      data: teachers
    });

  } catch (error) {
    console.error('获取课后老师列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 更新用户信息（仅管理员）
router.put('/:id', [
  authenticateToken,
  requireAdmin,
  body('name').optional().trim().notEmpty().withMessage('姓名不能为空'),
  body('role').optional().isIn(['admin', 'teacher', 'driver', 'after_school_teacher']).withMessage('无效的角色'),
  body('phone').optional().isMobilePhone('zh-CN').withMessage('手机号格式不正确'),

], async (req, res) => {
  try {
    // 验证输入
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '输入验证失败',
        errors: errors.array()
      });
    }

    const userId = req.params.id;
    const { name, role, phone, password } = req.body;

    // 检查用户是否存在
    const user = await getOne('SELECT id, role FROM users WHERE id = ?', [userId]);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    // 更新用户信息
    const updateFields = [];
    const updateValues = [];

    if (name) {
      updateFields.push('name = ?');
      updateValues.push(name);
    }
    if (role) {
      updateFields.push('role = ?');
      updateValues.push(role);
    }
    if (phone) {
      updateFields.push('phone = ?');
      updateValues.push(phone);
    }

    if (password) {
      updateFields.push('password = ?');
      updateValues.push(password);
    }

    if (updateFields.length === 0) {
      return res.status(400).json({
        success: false,
        message: '没有提供要更新的字段'
      });
    }

    updateFields.push('updated_at = CURRENT_TIMESTAMP');
    updateValues.push(userId);

    await executeQuery(`
      UPDATE users 
      SET ${updateFields.join(', ')} 
      WHERE id = ?
    `, updateValues);

    res.json({
      success: true,
      message: '用户信息更新成功'
    });

  } catch (error) {
    console.error('更新用户错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 删除用户（仅管理员）
router.delete('/:id', authenticateToken, requireAdmin, async (req, res) => {
  try {
    const userId = req.params.id;

    // 检查用户是否存在
    const user = await getOne('SELECT id, role FROM users WHERE id = ?', [userId]);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    // 不能删除管理员
    if (user.role === 'admin') {
      return res.status(400).json({
        success: false,
        message: '不能删除管理员用户'
      });
    }

    await executeQuery('DELETE FROM users WHERE id = ?', [userId]);

    res.json({
      success: true,
      message: '用户删除成功'
    });

  } catch (error) {
    console.error('删除用户错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

export default router;
